<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天室</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
        }
        #chat-container {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            height: 500px;
            overflow-y: auto;
            margin-bottom: 15px;
            background-color: white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        #message-input {
            width: 75%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        #send-button {
            width: 20%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-left: 5px;
            transition: background-color 0.3s;
        }
        #send-button:hover {
            background-color: #45a049;
        }
        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 8px;
            background-color: #f0f0f0;
            word-wrap: break-word;
        }
        .own-message {
            background-color: #d4edda;
            text-align: right;
        }
        .system-message {
            background-color: #d1ecf1;
            text-align: center;
            font-style: italic;
        }
        .message-info {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }
        #user-count {
            text-align: right;
            margin-bottom: 10px;
            color: #666;
            font-size: 14px;
        }
        #username-container {
            margin-bottom: 15px;
            text-align: center;
        }
        #username-input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        #set-username {
            padding: 8px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 5px;
        }
        #set-username:hover {
            background-color: #0069d9;
        }
    </style>
</head>
<body>
<h1>WebSocket 聊天室</h1>

<div id="username-container">
    <input type="text" id="username-input" placeholder="输入您的昵称">
    <button id="set-username" onclick="setUsername()">确定</button>
</div>

<div id="user-count">在线用户: <span id="user-count-number">0</span></div>

<div id="chat-container"></div>

<div>
    <input type="text" id="message-input" placeholder="输入消息..." disabled>
    <button id="send-button" onclick="sendMessage()" disabled>发送</button>
</div>

<script>
    let stompClient = null;
    let username = null;
    let userId = Math.random().toString(36).substring(2, 10);

    function setUsername() {
        const input = document.getElementById('username-input');
        const name = input.value.trim();

        if (name) {
            username = name;
            document.getElementById('username-container').style.display = 'none';
            document.getElementById('message-input').disabled = false;
            document.getElementById('send-button').disabled = false;
            connect();
        } else {
            alert('请输入有效的昵称');
        }
    }

    function connect() {
        // 确保使用正确的服务器地址和端口
        const socket = new SockJS('http://localhost:8081/websocket');
        stompClient = Stomp.over(socket);

        // 禁用心跳，减少潜在问题
        stompClient.heartbeat.outgoing = 0;
        stompClient.heartbeat.incoming = 0;

        stompClient.connect({},
            function(frame) {
                console.log('Connected: ' + frame);
                addSystemMessage('连接成功');

                stompClient.subscribe('/topic/public', function(message) {
                    console.log("Received: " + message.body);
                    try {
                        const data = JSON.parse(message.body);
                        // 处理消息...
                    } catch (e) {
                        console.error("Error parsing message: ", e);
                    }
                });
            },
            function(error) {
                console.log('连接错误: ' + error);
                addSystemMessage('连接断开，5秒后重试...');
                setTimeout(connect, 5000);
            }
        );
    }

    function sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();

        if (message && stompClient && username) {
            stompClient.send("/app/chat.sendMessage", {},
                JSON.stringify({
                    sender: username,
                    type: 'MESSAGE',
                    content: message
                })
            );
            input.value = '';
        }
    }

    function addMessageToChat(sender, message, type) {
        const chatContainer = document.getElementById('chat-container');
        const messageElement = document.createElement('div');

        messageElement.classList.add('message');
        if (type === 'own') {
            messageElement.classList.add('own-message');
        }

        const now = new Date();
        const timeString = now.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});

        messageElement.innerHTML = `
                <div class="message-info">${sender} · ${timeString}</div>
                <div>${message}</div>
            `;
        chatContainer.appendChild(messageElement);

        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    function addSystemMessage(message) {
        const chatContainer = document.getElementById('chat-container');
        const messageElement = document.createElement('div');

        messageElement.classList.add('message', 'system-message');
        messageElement.textContent = message;
        chatContainer.appendChild(messageElement);

        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 事件监听
    document.getElementById('message-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // 窗口关闭时发送离开通知
    window.addEventListener('beforeunload', function() {
        if (stompClient && username) {
            stompClient.send("/app/chat.addUser", {},
                JSON.stringify({sender: username, type: 'LEAVE', content: ''})
            );
        }
    });
</script>
</body>
</html>